<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入用户ID"
      />
      <!-- <el-input
        v-model="listQuery.orderId"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入订单ID"
      /> -->
      <el-input
        v-model="listQuery.orderSn"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入订单编号"
      />
      <el-date-picker
        v-model="listQuery.timeArray"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item"
        range-separator="至"
        start-placeholder="下单开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      />
      <el-select
        v-model="listQuery.orderStatusArray"
        multiple
        style="width: 200px"
        class="filter-item"
        placeholder="请选择订单状态"
      >
        <el-option
          v-for="(key, value) in statusMap"
          :key="key"
          :label="key"
          :value="value"
        />
      </el-select>

      <el-input
        v-model="listQuery.userName"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入名称"
      />
      <el-input
        v-model="listQuery.mobile"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入用户手机号"
      />
      <el-input
        v-model="listQuery.inviteCode"
        clearable
        class="filter-item"
        style="width: 160px"
        placeholder="请输入用户账号"
      />
      <el-select
        v-model="listQuery.identification"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择冷冻非冷冻"
      >
        <el-option
          v-for="(key, value) in identificationMap"
          :key="key"
          :label="key"
          :value="value"
        />
      </el-select>
      <el-button
        v-permission="['GET /admin/order/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button
      >
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button
      >
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="add"
      >添加</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        align="center"
        min-width="100"
        label="订单编号"
        prop="orderSn"
      />

      <el-table-column align="center" label="用户ID" prop="userId" />

      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.orderStatus == 100"
            style="color: white; background: #d5d203"
          >完成</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 101"
            style="color: white; background: #97dc00"
          >未付款</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 102"
            style="color: white; background: #ff2eac"
          >用户取消</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 103"
            style="color: white; background: #904cbb"
          >系统取消</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 205"
            style="color: white; background: #0cb4b4"
          >待发货</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 502"
            style="color: white; background: #ff0000"
          >申请退款</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 501"
            style="color: #666666; background: #e6e6e6"
          >已退款</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 301"
            style="color: white; background: #5eff5e"
          >待收货</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 401"
            style="color: white; background: #ff9292"
          >用户收货</el-tag
          >
          <el-tag
            v-if="scope.row.orderStatus == 402"
            style="color: white; background: #36d051"
          >系统收货</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称" prop="userName" />
      <el-table-column align="center" label="用户手机号" prop="mobile" />
      <el-table-column align="center" label="用户账号" prop="inviteCode" />

      <el-table-column align="center" label="订单金额" prop="goodsPrice" />

      <el-table-column align="center" label="运费" prop="freightPrice" />

      <el-table-column align="center" label="支付金额" prop="orderPrice" />

      <el-table-column align="center" label="下单时间" prop="addTime" />

      <el-table-column align="center" label="支付时间" prop="payTime" />
<el-table-column align="center" label="取貨日期" prop="picktime" />
      <el-table-column align="center" label="订单pv" prop="pv" />
      <!-- <el-table-column align="center" label="物流单号" prop="shipSn" />

      <el-table-column align="center" label="物流渠道" prop="shipChannel" />-->

      <el-table-column
        align="center"
        label="操作"
        width="450"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/order/updStateById']"
            type="primary"
            size="mini"
            @click="showUpd(scope.row)"
          >修改状态</el-button
          >
          <el-button
            v-permission="['GET /admin/order/detail']"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
          >详情</el-button
          >
          <el-button
            v-if="scope.row.orderStatus == 201 || scope.row.orderStatus == 205"
            v-permission="['POST /admin/order/ship']"
            type="primary"
            size="mini"
            @click="handleShip(scope.row)"
          >发货</el-button
          >
          <el-button
            v-if="scope.row.atmPayStatus == 1"
            v-permission="['POST /admin/order/updateAtmPayStatus']"
            type="primary"
            size="mini"
            @click="handleAtm(scope.row)"
          >凭证审核</el-button
          >
          <el-button
            v-if="scope.row.orderStatus == 502"
            v-permission="['POST /admin/order/refund']"
            type="primary"
            size="mini"
            @click="handleRefund(scope.row)"
          >同意退款</el-button>
          <el-button
            v-if="scope.row.orderStatus == 502"
            v-permission="['POST /admin/order/refund']"
            type="primary"
            size="mini"
            @click="handleRefused(scope.row)"
          >拒绝退款</el-button>
          <el-button
            v-if="scope.row.orderStatus == 301"
            v-permission="['POST /admin/order/update']"
            type="primary"
            size="mini"
            @click="wanok(scope.row)"
          >完成</el-button
          >
          <el-button
         
            v-permission="['GET /admin/order/deliveryNote']"
            type="primary"
            size="mini"
            @click="deliveryNote(scope.row)"
          >送货单</el-button
          >
          <el-button
            v-permission="['POST /admin/order/delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800">
      <section ref="print">
        <el-form :data="orderDetail" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ orderDetail.order.orderSn }}</span>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-tag>{{
              orderDetail.order.orderStatus | orderStatusFilter
              }}</el-tag>
          </el-form-item>
          <el-form-item label="订单用户">
            <span>{{ orderDetail.user.surname  }}{{ orderDetail.user.username  }}</span>
          </el-form-item>
          <el-form-item label="用户留言">
            <span>{{ orderDetail.order.message }}</span>
          </el-form-item>
          <el-form-item label="自提时间">
            <span>{{ orderDetail.order.picktime }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <span>（收货人）{{ orderDetail.order.consignee}}</span>
            <span>（手机号）{{ orderDetail.order.mobile }}</span>
            <span>（地址）{{ orderDetail.order.address | replaceval }}</span>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table
              :data="orderDetail.orderGoods"
              border
              fit
              highlight-current-row
            >
              <el-table-column
                align="center"
                label="商品名称"
                prop="goodsName"
              />
              <el-table-column align="center" label="商品编号" prop="artNo" />
              <el-table-column
                align="center"
                label="货品规格"
                prop="specifications"
              />
              <el-table-column align="center" label="货品价格" prop="price" />
              <el-table-column align="center" label="货品数量" prop="number" />
              <el-table-column align="center" label="货品图片" prop="picUrl">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl" width="40" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="费用信息">
            <span>
              (实际费用){{ orderDetail.order.orderPrice }}元 = (商品总价){{
                orderDetail.order.goodsPrice
              }}元 + (快递费用){{ orderDetail.order.freightPrice }}元 -
              (优惠码减免){{ orderDetail.order.promoCodePrice }}元 -
              (优惠券减免){{ orderDetail.order.couponPrice }}元
            </span>
          </el-form-item>
          <el-form-item label="支付信息">
            <span>（支付渠道）{{ payTypes[orderDetail.order.payType-1] }}</span>
            <span>（支付时间）{{ orderDetail.order.payTime }}</span>
          </el-form-item>
          <el-form-item label="快递信息">
            <span>（快递公司）{{ orderDetail.order.shipChannel }}</span>
            <span>（快递单号）{{ orderDetail.order.shipSn }}</span>
            <span>（发货时间）{{ orderDetail.order.shipTime }}</span>
          </el-form-item>
          <el-form-item v-if="chilis == 1">
            <span>（快递公司）{{ orderDetail.chil.shipChannel }}</span>
            <span>（快递单号）{{ orderDetail.chil.shipSn }}</span>
            <span>（发货时间）{{ orderDetail.chil.shipTime }}</span>
          </el-form-item>
          <el-form-item label="退款信息">
            <span>（退款金额）{{ orderDetail.order.refundAmount }}元</span>
            <span>（退款类型）{{ orderDetail.order.refundType }}</span>
            <span>（退款备注）{{ orderDetail.order.refundContent }}</span>
            <span>（退款时间）{{ orderDetail.order.refundTime }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <span>（确认收货时间）{{ orderDetail.order.confirmTime }}</span>
          </el-form-item>
          <el-form-item label="支付凭证">
            <span>
              <img :src="orderDetail.certificateUrl" v-show="orderDetail.certificateUrl && orderDetail.certificateUrl!=''" alt="" width="100px" height="100">
            </span>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">打 印</el-button>
      </span>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" title="发货">
      <el-form
        ref="shipForm"
        :model="shipForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-tag v-if="identification == 0">非冷冻订单</el-tag>
        <el-tag v-if="identification == 1">冷冻订单</el-tag>
        <el-form-item label="快递公司" prop="shipChannel">
          <el-input
            v-if="isshipChannel"
            v-model="shipForm.shipChannel"
            disabled
          />
          <el-input v-if="!isshipChannel" v-model="shipForm.shipChannel" />
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input v-if="isshipSn" v-model="shipForm.shipSn" disabled />
          <el-input v-if="!isshipSn" v-model="shipForm.shipSn" />
        </el-form-item>
      </el-form>

      <el-form
        v-if="this.subOrder == 1"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-tag>冷冻订单</el-tag>
        <el-form-item label="快递公司" prop="chilshipChannel">
          <el-input
            v-if="ischilshipChannel"
            v-model="shipForm.chilshipChannel"
            disabled
          />
          <el-input
            v-if="!ischilshipChannel"
            v-model="shipForm.chilshipChannel"
          />
        </el-form-item>
        <el-form-item label="快递编号" prop="chilshipSn">
          <el-input
            v-if="ischilshipSn"
            v-model="shipForm.chilshipSn"
            disabled
          />
          <el-input v-if="!ischilshipSn" v-model="shipForm.chilshipSn" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确定</el-button>
      </div>
    </el-dialog>

    <!-- 送货单对话框 -->
    <el-dialog :visible.sync="deliveryNoteVisible" title="送货单">
      <el-form
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item v-if="identification == 0" label="非冷冻送货单">
          <el-button type="danger" @click="download(0)">下载</el-button>
        </el-form-item>
        <el-form-item v-if="identification == 1" label="冷冻送货单">
          <el-button type="danger" @click="download(1)">下载</el-button>
        </el-form-item>
      </el-form>
      <el-form
        v-if="this.subOrder == 1"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="冷冻送货单">
          <el-button type="danger" @click="download(1)">下载</el-button>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="deliveryNoteVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改状态对话框 -->
    <el-dialog :visible.sync="showUpdVisible" title="修改订单状态">
      <el-form
        ref="shipForm"
        :model="shipForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="订单状态" prop="shipChannel">
          <el-select
            style="width: 200px"
            placeholder="请选择订单状态"
            v-model="orderStatus"
          >
            <el-option
              v-for="item in updStatusMap"
              :key="item.value"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showUpdVisible = false">取消</el-button>
        <el-button type="primary" @click="updState">确定</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" title="退款">
      <el-form
        ref="refundForm"
        :model="refundForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="退款金额" prop="refundMoney">
          <el-input v-model="refundForm.refundMoney" :disabled="true" />
        </el-form-item>
        <el-form-item label="退款原因" prop="refundContent">
          <el-input
            type="textarea"
            v-model="refundForm.refundContent"
            :disabled="true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible2" title="退款">
      <el-form
        ref="refundForm2"
        :model="refundForm2"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="拒绝原因" prop="ordertext">
          <el-input
            type="textarea"
            v-model="refundForm2.ordertext"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund2">确定</el-button>
      </div>
    </el-dialog>

    <!--atm凭证审核 -->
    <el-dialog :visible.sync="atmFormDialogVisible" title="凭证审核">
      <el-form
        ref="atmForm"
        :model="atmForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <template>
          <img :src="atmimg" class="tu" @click="atmda(atmimg)" />
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="atmping(false)">拒绝</el-button>
        <el-button type="primary" @click="atmping(true)">审核通过</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="downVisible" title="送货单信息">
      <div id="pdfDom" style="padding-top: 55px; background-color: #fff">
        <div class="printBox" v-show="isDown">
          <div class="printlogo">
            <img src="@/assets/logo.png" alt="" />
          </div>
          <div class="printTitle">送货单</div>
          <div class="printDetailed">
            <div class="detailLeft">
              <div>
                <div>订单编号</div>
                <div>{{ downData.orderSn }}</div>
              </div>
              <div>
                <div>收件人</div>
                <div>{{ downData.userId }}</div>
              </div>
              <div>
                <div>联络电话</div>
                <div>{{ downData.mobile }}</div>
              </div>
              <div>
                <div>送货到</div>
                <div>{{ downData.address | replaceval }}</div>
              </div>
            </div>
            <div class="detailRight">
              <div>
                <div>制单日期</div>
                <div>{{ downData.addTime }}</div>
              </div>
              <div>
                <div>制单员</div>
                <div style="font-weight:600">{{ downData.shipUser }}</div>
              </div>
              <div>
                <div>送货单编号</div>
                <div>{{ downData.shipSn }}</div>
              </div>
              <div>
                <div>送货日期及时间</div>
                <div>{{ downData.shipTime }}</div>
              </div>
              <div>
                <div>运送方式</div>
                <div style="font-weight:600">{{ downData.shipType }}</div>
              </div>
            </div>
          </div>
          <div class="printTable">
            <el-table
              :data="orderGoodsList"
              style="width: 100%"
              size="mini"
            >
              <el-table-column
                label="编号"
                align="center"
                type="index"
                width="50"
              >
              </el-table-column>
              <el-table-column label="照片" align="center" width="120">
                <template slot-scope="scope">
                  <img :src="scope.row.picUrl"/>
                </template>
              </el-table-column>
              <el-table-column label="商品编号" align="center">
                <template slot-scope="scope">
                  {{ scope.row.artNo }}
                </template>
              </el-table-column>
              <el-table-column label="商品名称" align="center">
                <template slot-scope="scope">
                  {{ scope.row.goodsName }}
                </template>
              </el-table-column>
              <el-table-column label="属性" align="center">
                <template slot-scope="scope">
                  {{ scope.row.categoryName }}
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center">
                <template slot-scope="scope">
                  {{ scope.row.number }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- <div class="printBei">
            <div>备注</div>
            <div>请安排B时段送货</div>
          </div> -->
          <div class="printSure">
            <div>确认及接受此单</div>
            <div></div>
            <div>日期</div>
          </div>
          <div class="printFooter">
            <div>幸福滋味 Home Tasty</div>
            <div>www.hometasty.hk</div>
            <div>📞 55404238</div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="downVisible = false">取消</el-button>
        <el-button type="primary" @click="downSure(true)">确定下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    detailOrder,
    listOrder,
    listChannel,
    refundOrder,
    detok,
    refused,
    deleteOrder,
    shipOrder,
    atmReplay,
    getAtmPic,
    split,
    updStateById,
    excelOrder,
    delivery,
  } from "@/api/order";
  import {
    detailGoods,detailGoods2
  } from "@/api/goods";

import { userDetail,userDetail2 } from '@/api/user'
import { findOrders2 } from '@/api/pv'
  
  import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
  import checkPermission from "@/utils/permission"; // 权限判断函数
  import { downloadPDF } from "@/utils/test";
  import { readStorage } from "@/api/storage";
  const statusMap = {
    100: "完成",
    101: "未付款",
    102: "用户取消",
    103: "系统取消",
    205: "待发货",
    502: "申请退款",
    501: "已退款",
    301: "待收货",
    401: "用户收货",
    402: "系统收货",
  };
  const identificationMap = {
    0: "冷冻",
    1: "非冷冻",
  };

  const updStatusMap = [
    { key: 101, value: "未付款" },
    { key: 205, value: "待发货" },
    { key: 301, value: "待收货" },
    { key: 401, value: "待评价" },
    { key: 100, value: "完成" },
    { key: 102, value: "取消" },
    { key: 501, value: "已退款" },
  ];

  export default {
    name: "Order",
    components: { Pagination },
    filters: {
      orderStatusFilter(status) {
        return statusMap[status];
      },
      replaceval:function(data){
        return data && data.replace('值','')
      }
    },
    data() {
      return {
        statusMap : {
            100: "完成",
            101: "未付款",
            102: "用户取消",
            103: "系统取消",
            205: "待发货",
            502: "申请退款",
            501: "已退款",
            301: "待收货",
            401: "用户收货",
            402: "系统收货",
        },
        payTypes:[
           'PayPal支付','FirstPay支付','ATM支付','现金支付','八達通支付','VISA支付','Master支付','銀聯支付','EPS支付','支付寶 (Alipay)支付','微信支付(WeChat Pay)支付','其他支付'
        ],
        userLevel1:  ['普通会员', '经销商', '副总监', '总监', '区域总监','高级区域总监', '亚洲总监', '亚太区总监', '环球总监'],
        userLevel2:  ['普通會員', '經銷商', '副總監', '總監', '區域總監','高級區域總監', '亞洲總監', '亞太區總監', '環球總監'],
        orderStatus: "完成",
        list: [],
        list1: null,
        id: "",
        total: 0,
        listLoading: true,
        atmimg: "",
        atmFormDialogVisible: false,
        listQuery: {
          page: 1,
          limit: 20,
          id: undefined,
          name: undefined,
          timeArray: [],
          orderStatusArray: [],

          sort: "add_time",
          order: "desc",
          orderId: undefined,
          userName: "",
          mobile: "",
          inviteCode: "",
          identification: "",
        },
        atmForm: {
          orderSn: undefined,
        },
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
        statusMap,
        updStatusMap,
        identificationMap,
        orderDialogVisible: false,
        orderDetail: {
          order: {},
          user: {},
          orderGoods: [],
          chil: {},
        },
        shipForm: {
          orderId: undefined,
          shipChannel: undefined,
          shipSn: undefined,
          ocId: undefined,
          chilshipChannel: undefined,
          chilshipSn: undefined,
        },
        shipDialogVisible: false,
        subOrder: 0,
        refundForm: {
          orderId: undefined,
          refundMoney: undefined,
          refundContent: undefined,
        },
        refundForm2: {
          ordersn: undefined,
          modify: 1,
          ordertext: undefined,
        },
        chilis: 0,
        refundDialogVisible: false,
        refundDialogVisible2: false,
        downloadLoading: false,
        channels: [],
        showUpdVisible: false,
        deliveryNoteVisible: false,
        identification: 0,

        downData: {},
        orderGoodsList: [],
        isDown: false,
        downVisible: false,
        isshipChannel: false,
        isshipSn: false,
        ischilshipChannel: false,
        ischilshipSn: false,
      };
    },
    created() {
      this.getList();
      // this.getChannel()
    },
    methods: {
      checkPermission,
      getList() {        
        this.listLoading = true;
        if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
          this.listQuery.start = this.listQuery.timeArray[0];
          this.listQuery.end = this.listQuery.timeArray[1];
        } else {
          this.listQuery.start = null;
          this.listQuery.end = null;
        }
        if (this.listQuery.orderId) {
          detailOrder(this.listQuery.orderId)
            .then((response) => {
              this.list = [];
              if (response.data.data.order) {
                this.list.push(response.data.data.order);
                this.total = 1;
                this.listLoading = false;
              }
            })
            .catch(() => {
              this.list = [];
              this.total = 0;
              this.listLoading = false;
            });
        } else {
          listOrder(this.listQuery)
            .then(async (response) => {
              let list = response.data.data.list;
              for (let index = 0; index < list.length; index++) {
                const element = list[index];
                let response2=await findOrders2({userId:element.userId,limit:999,page:1})
                for (let index = 0; index < response2.data.data.list.length; index++) {
                  const element2 = response2.data.data.list[index];
                  if(element2.orderSn==element.orderSn){
                    element.pv=element2.orderPv
                  }
                }
              }
              this.list=list
              
              this.total = response.data.data.total;
              this.listLoading = false;
            })
            .catch(() => {
              this.list = [];
              this.total = 0;
              this.listLoading = false;
            });
        }
      },
      add() {
        this.$router.push({
          path: "/mall/OrderOV",
        });
      },
      atmping(e) {
        atmReplay({ agreeIs: e, orderSn: this.atmForm.orderSn })
          .then((response) => {
            this.atmFormDialogVisible = false;
            this.$notify.success({
              title: "成功",
              message: "操作成功",
            });
            this.getList();
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
            this.listLoading = false;
          });
      },
      handleAtm(row) {
        this.atmForm.orderSn = row.orderSn;
        this.atmFormDialogVisible = true;
        getAtmPic(row.id).then((res) => {
          if (res.data.errno == 0) {
            this.atmimg = res.data.data.certificateUrl;
          }else{
                  this.atmimg = ''
                }
        });
      },
      getChannel() {
        listChannel().then((response) => {
          this.channels = response.data.data;
        });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handleDetail(row) {
        detailOrder(row.id).then(async (response) => {
          let orderDetail = response.data.data;
          
          let response3= await userDetail2(row.userId)
          this.$set(this.orderDetail,'user',response3.data.data)
          for (let index = 0; index < orderDetail.orderGoods.length; index++) {
            const element = orderDetail.orderGoods[index];
            let response2=await detailGoods2(element.goodsId)
            element['artNo']  =response2.data.data.goods.artNo;
          }
            this.$set(this.orderDetail,'orderGoods',orderDetail.orderGoods)
            this.$set(this.orderDetail,'order',orderDetail.order)
    
          getAtmPic(row.id).then((res) => {
                if (res.data.errno == 0) {
                  this.$set(this.orderDetail,'certificateUrl',res.data.data.certificateUrl)
                }else{
                  this.$set(this.orderDetail,'certificateUrl','')
                }
              },(err)=>{
                this.$set(this.orderDetail,'certificateUrl','')
              });
          var chil = this.orderDetail.chil;
          if (chil != null) {
            this.chilis = 1;
          } else {
            this.chilis = 0;
          }
        });
        this.orderDialogVisible = true;
      },
      updState(row) {

        updStateById({ id: this.id, orderStatus: this.orderStatus })
          .then((response) => {
            this.showUpdVisible = false;
            this.$notify.success({
              title: "成功",
              message: "修改订单成功",
            });
            this.getList();
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      },
      wanok(row) {
        detok(row.orderSn).then((response) => {
          this.$notify.success({
            title: "成功",
            message: "成功",
          });
          this.getList();
        });
      },
      download(isFrozen) {

        delivery(this.shipForm.orderId, isFrozen).then((response) => {
          if (response.data.errno == 0) {
            this.downData = response.data.data;
            this.orderGoodsList = response.data.data.orderGoodsList;

            detailOrder(this.shipForm.orderId).then((response3) => {
              let data
                let orderDetail = response3.data.data;
                for (let index = 0; index < orderDetail.orderGoods.length; index++) {
                  const element = orderDetail.orderGoods[index];
                  detailGoods(element.goodsId).then((response2) => {
                      data=this.orderGoodsList[index]
                      data['artNo']=response2.data.data.goods.artNo
                     
                  });
              }
              setTimeout(() => {
                this.$set(this.orderGoodsList,'index',data)
              }, 1000);
            });

            this.isDown = true;
            this.downVisible = true;
          } else {
            this.orderGoodsList = [];
            this.downData = {};
            this.isDown = false;
          }
        });
      },
      godown() {
        downloadPDF(document.querySelector("#pdfDom"), "送貨單");
      },
      downSure() {
        this.downVisible = false;
        // setTimeout(() => {
        this.godown();
        // }, 3000);
      },
      deliveryNote(row) {
        split(row.id)
          .then((response) => {
            var resut = response.data.data;
            this.shipForm.orderId = resut.data.orderId;
            var chilList = resut.data.splitList;
            this.identification = resut.data.identification;
            this.deliveryNoteVisible = true;
            if (chilList.length > 0) {
              this.subOrder = 1;
            } else {
              this.subOrder = 0;
            }
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      },
      handleShip(row) {
        split(row.id)
          .then((response) => {
            var resut = response.data.data;
            this.shipForm.orderId = resut.data.orderId;
            this.shipForm.shipChannel = resut.data.shipChannel;
            this.shipForm.shipSn = resut.data.shipSn;
            var chilList = resut.data.splitList;
            this.identification = resut.data.identification;
            this.shipDialogVisible = true;
            if (chilList.length > 0) {
              this.subOrder = 1;
              this.shipForm.chilshipChannel = chilList[0].shipChannel;
              this.shipForm.chilshipSn = chilList[0].shipSn;
              this.shipForm.ocId = chilList[0].ocId;
            } else {
              this.subOrder = 0;
              this.shipForm.ocId = 0;
            }

            if (resut.data.shipChannel != null && resut.data.shipChannel != "") {
              this.isshipChannel = true;
            } else {
              this.isshipChannel = false;
            }
            if (resut.data.shipSn != null && resut.data.shipSn != "") {
              this.isshipSn = true;
            } else {
              this.isshipSn = false;
            }
            if (
              this.shipForm.chilshipChannel != null &&
              this.shipForm.chilshipChannel != ""
            ) {
              this.ischilshipChannel = true;
            } else {
              this.ischilshipChannel = false;
            }
            if (
              this.shipForm.chilshipSn != null &&
              this.shipForm.chilshipSn != ""
            ) {
              this.ischilshipSn = true;
            } else {
              this.ischilshipSn = false;
            }
            this.$nextTick(() => {
              this.$refs["shipForm"].clearValidate();
            });
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      },
      showUpd(row) {
        this.showUpdVisible = true;
        this.orderStatus = row.orderStatus;
        this.id = row.id;
      },
      confirmShip() {
        this.$refs["shipForm"].validate((valid) => {
          if (valid) {
            shipOrder(this.shipForm)
              .then((response) => {
                if (response.data.errno != 0) {
                  this.$notify.error({
                    title: "失败",
                    message: response.data.errmsg,
                  });
                } else {
                  this.shipDialogVisible = false;
                  this.$notify.success({
                    title: "成功",
                    message: "确认发货成功",
                  });
                  this.getList();
                }
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg,
                });
              });
          }
        });
      },
      handleDelete(row) {
        deleteOrder({ orderId: row.id })
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "订单删除成功",
            });
            this.getList();
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      },
      handleRefused(row){
        this.refundForm2.ordersn = row.orderSn;
        this.refundDialogVisible2 = true;
        this.$nextTick(() => {
          this.$refs["refundForm2"].clearValidate();
        });
      },
      handleRefund(row) {
        this.refundForm.orderId = row.id;
        this.refundForm.refundMoney = row.orderPrice;
        this.refundForm.refundContent = row.refundContent;
        this.refundDialogVisible = true;
        this.$nextTick(() => {
          this.$refs["refundForm"].clearValidate();
        });
      },
      confirmRefund2() {
        this.$refs["refundForm2"].validate((valid) => {
          if (valid) {
            refused(this.refundForm2)
              .then((response2) => {
                this.refundDialogVisible2 = false;
                this.$notify.success({
                  title: "成功",
                  message: "拒绝成功",
                });
                this.getList();
              })
              .catch((response2) => {
                console.log(response2)
              });
          }
        });
      },
      confirmRefund() {
        this.$refs["refundForm"].validate((valid) => {
          if (valid) {
            refundOrder(this.refundForm)
              .then((response) => {
                this.refundDialogVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "确认退款成功",
                });
                this.getList();
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.errmsg,
                });
              });
          }
        });
      },
      contains(arr, obj) {
        console.log(arr, obj)
        var i = arr.length;
        while (i--) {
            if (arr[i] == obj) {
                return i;
            }
        }
        return false;
    },
      handleDownload() {
        excelOrder(this.listQuery)
          .then((response) => {
            this.list1 = response.data.data.list;
 
            for (let index = 0; index < this.list1.length; index++) {
              const element = this.list1[index];
              element['pv']=element.integralPrice
    
             
              element.postName= this.userLevel2[element.post-1]
              element.address=element.address.replace('值','')

              element.integralPrice=0
              element.goodsPrice=0
              element.payType= element.payType==3?'ATM支付':'paypal'
                element.orderStatusName=this.statusMap[element.orderStatus]
            }

            import("@/vendor/Export2Excel").then((excel) => {
              const tHeader = [
                "订单编号",
                "订单日期",
                "会员级别",
                "会员姓名",
                "手机号码",
                "商品SKU",
                "商品名称",
                "商品分类",
                "商品数量",
                "推广折扣",
                "优惠券折扣",
                "自定义折扣",
                "订单统计",
                "支付金额",
                "付款方式",
                "配送地址",
                "配送方式",
                "pv",
                "状态",
              ];
              const filterVal = [
                "orderSn",
                "addTime",
                "postName",
                "userName",
                "userMobile",
                "goodsSn",
                "goodsName",
                "categoryName",
                "number",
                "grouponPrice",
                "integralPrice",
                "goodsPrice",
                "orderPrice",
                "actualPrice",
                "payType",
                "address",
                "shipChannel",
                "pv",
                "orderStatusName",
              ];
              excel.export_json_to_excel2(
                tHeader,
                this.list1,
                filterVal,
                "订单信息"
              );
              this.downloadLoading = false;
            });
          })
          .catch(() => {
            this.list1 = [];
            this.downloadLoading = false;
          });
      },
      printOrder() {
        this.$print(this.$refs.print);
        this.orderDialogVisible = false;
      },
    },
  };
</script>
<style scoped>
  .tu {
    width: 100%;
  }
  .printBox {
    /* padding: 50px 20px; */
    box-sizing: border-box;
    width: 90%;
    margin: 0px auto;
  }
  .printlogo > img {
    width: 200px;
    height: auto;
  }
  .printTitle {
    margin: 20px auto;
    font-size: 30px;
    font-weight: 500;
    text-align: center;
    box-sizing: border-box;
  }
  .printDetailed {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    color: black;
  }
  .detailLeft,
  .detailRight {
    width: 50%;
  }
  .detailLeft > div,
  .detailRight > div {
    display: flex;
    box-sizing: border-box;
    align-items: center;
    width: 100%;
  }
  .printDetailed > div > div > div:nth-child(1) {
    width: 35%;
    line-height: 30px;
    font-weight: 500;
  }
  .printDetailed > div > div > div:nth-child(2) {
    width: 60%;
    word-break: break-word;
  }
  .printTable{
    margin: 20px 0px;
  }
  .printTable img {
    width: 100px;
    height: auto;
  }
  .printBei {
    display: flex;
    align-items: center;
    margin: 20px 0px;
  }
  .printBei > div:nth-child(1) {
    font-weight: 600;
    width: 100px;
  }
  .printSure {
    width: 250px;
    float: right;
    right: 0px;
    margin-top: 30px;
  }
  .printSure > div:nth-child(1) {
    font-weight: 600;
  }
  .printSure > div:nth-child(2) {
    width: 100%;
    height: 1px;
    background: rgb(66, 66, 66);
    margin-top: 100px;
    margin-bottom: 10px;
  }
  .printSure > div:nth-child(3) {
    font-weight: 600;
  }
  .printFooter {
    width: 100%;
    margin-top: 400px;
    text-align: center;
  }
  .printFooter > div:nth-child(2) {
    font-weight: 550;
  }
  #pdfDom >>> .el-table .el-table__header {
    border-top: 1px solid black !important;
    border-bottom: 1px solid black !important;
  }
  #pdfDom >>> .el-table th {
    color: black;
  }
  #pdfDom >>> .el-table td,
  .el-table th.is-leaf {
    /* border: 1px solid #ebeef5; */
  }
  #pdfDom >>> .el-table--border th,
  .el-table__fixed-right-patch {
    /* border: 1px solid #ebeef5; */
  }
</style>
